package com.zhishusoft.wordtemplatedemo.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zhishusoft.wordtemplatedemo.service.WordTempService;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@Slf4j
public class FileController {
	
	public static volatile String currtFileName= "";  
	
	@Autowired
	private WordTempService WordTempService;
	
	@RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
            if(!"docx".equals(suffixName)) {
            	return "请上传docx的word";
            }
            log.info("文件的后缀名为：" + suffixName);
            String preName = fileName.substring(0,fileName.lastIndexOf("."));
            log.info("文件的简名（不包含后缀）为：" + preName);
            // 设置文件存储路径
            String filePath = "c:/word/";
            String path = filePath + fileName;
            currtFileName = filePath + preName;
            //把文件地址存入threadLocal
//            FileNameContext.setFileName(filePath + preName);
            
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }
	
	@GetMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response,String url,
    		String username, String password, @RequestParam Map<String, String> tables, String parametersMap) {
		//获取网络路径
		StringBuffer serverBasePath = new StringBuffer();
		serverBasePath.append(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath());		
		
		//解析tables json数据
		Map<String, Object> jsonMap= jsonToMap(tables.get("tables"));
		
		
		String fileName = WordTempService.execute(url, username, password, jsonMap, parametersMap);
        if (fileName != null && !"fail".equals(fileName)) {
            //设置文件路径
            File file = new File(fileName);
            String newFileName = file.getName();
            
            String urll = serverBasePath + "/static/img/" + newFileName;
            return "{\"firstUrl\":" + "\"" + urll +"\"" + "}";
            //File file = new File(realPath , fileName);
//            if (file.exists()) {
////                response.setContentType("application/force-download");// 设置强制下载不打开
//                response.addHeader("Content-Disposition", "attachment;fileName=" + "fsdfsd.docx");// 设置文件名
//                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");//设置文件类型
//                byte[] buffer = new byte[1024];
//                FileInputStream fis = null;
//                BufferedInputStream bis = null;
//                try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
//                    OutputStream os = response.getOutputStream();
//                    int i = bis.read(buffer);
//                    while (i != -1) {
//                        os.write(buffer, 0, i);
//                        i = bis.read(buffer);
//                    }
//                    return "下载成功";
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally {
//                    if (bis != null) {
//                        try {
//                            bis.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    if (fis != null) {
//                        try {
//                            fis.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }
        }
        return "下载失败";
    }
	
	
	 /**
     * 将json字符串转为Map对象
     * 如果json复杂，结果可能是map嵌套map
     * @param jsonStr 入参，json格式字符串
     * @return 返回一个map
     */
     private Map<String, Object> jsonToMap(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        if(jsonStr != null && !"".equals(jsonStr)){
            //最外层解析
            JSONObject json = JSONObject.fromObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                //如果内层还是数组的话，继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<JSONObject> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = it.next();
                        list.add(jsonToMap(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        }else{
            return null;
        }
    }

}
